$(function(){
    //注册搜索行为
    $(document).on('click', '.sc_btn_search', function (event) {
        event.preventDefault();
        var url = $('.sc_search_form').attr('action');
        var split = url.indexOf('?') === -1 ? '?' : '&';
        window.location.href = '#' + parseUri(url + split + $('.sc_search_form').serialize());
    });
    //注册ajax加载行为
    $(document).on('click', '[data-url]', function (event) {
        event.preventDefault();
        href($(this).attr('data-url'), this);
        $('.layui-tab-content').find('a').removeClass('active');
        var spm = GetQueryString('spm');
        $('[data-menu-node="' + spm + '"]').eq(0).addClass('active');
    });
    //注册侧边菜单点击行为
    $(document).on('click', '.sc_side_tab .layui-tab-title li', function (event) {
        event.preventDefault();
        setTimeout(function(){
            return $('.layui-show').find('.sc_side_menu li:first-child a').trigger('click');
        }, 10);
    });
    //注册刷新菜单点击行为
    $(document).on('click', '.tree_reload', function (event){
        var btn = $(this);
        event.preventDefault();
        $.post('/sitenode/getnode.html', {}, function(data){
            btn.next('ul').html(data);
            return btn.next('ul').find('li:first-child a').trigger('click');
        });
    });
});
layui.use(['element','layer','form','laydate','laypage'], function(){
    var element = layui.element,
        layer = layui.layer,
        laydate = layui.laydate,
        laypage = layui.laypage,
        form = layui.form;
    window.onload = function() {
        if(!window.location.hash){
            return $('.layui-show').find('.sc_side_menu li:first-child a').trigger('click');
        }else{
            var spm = GetQueryString('spm');
            $('[data-menu-node="' + spm + '"]').eq(0).addClass('active');
            position = spm.split("-");
            element.tabChange('nav', position[1]);
            var hash = window.location.hash.substr(1);
            open(hash);
        }
    }
    window.onhashchange = function () {
        var hash = (window.location.hash || '').substring(1),
        node = hash.replace(/.*spm=([\d\-m]+).*/ig, "$1");
        if (!/^m\-[\d\-]+$/.test(node)) {
            node = queryNode(getUri()) || '';
        }
        open(hash);
    };
    //表单验证
    $(".layui-form").Validform({
        tiptype:3,
        ajaxPost:true,
        callback:function(data){
            showTip(data);
        }
    });
    //移动判断
    form.on('select(category)', function(data){
        if(data.value!=='0'){
            $('.btn-mobile').removeAttr("disabled").removeClass("layui-btn-disabled");
        }else{
            $(".btn-mobile").attr("disabled", true).addClass("layui-btn-disabled");
        }
    });
    //绑定弹出事件
    $(document).on('click','[data-open]',function(event){
        event.preventDefault();
        var url = $(this).data('open'),
            title = $(this).attr('data-title');
        $.post(url, {}, function(data){
            layer.open({
                type: 1,
                title: title,
                area: ['800px',''],
                content: data,
                fixed: false,
                resize: false,
                scrollbar: false,
                success: function(layero, index){
                    $(".layui-form").Validform({
                        tiptype:3,
                        ajaxPost:true,
                        beforeSubmit:function(curform){
                            $.post($('#form').attr('action'),$('#form').serialize(),function(data){
                                showTip(data);
                            });
                    		return false;
                    	},
                    });
                    form.render();
                }
            });
        });
    });
    $(document).on('click','[data-iframe]',function(event){
        event.preventDefault();
        var url = $(this).data('iframe'),
            title = $(this).attr('data-title');
        layer.open({
            type: 2,
            title: title,
            area: ['800px','85%'],
            content: url,
            fixed: false,
            resize: false
        });
    });
    //绑定confirm事件
    $(document).on('click','[data-confirm]',function(event){
        event.preventDefault();
        var url = $(this).data('confirm');
        layer.confirm('您确认操作吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url,function(data){
                showTip(data);
            });
        }, function(){});
    });
    $(document).on('click','[data-action]',function(event){
        event.preventDefault();
        var url = $(this).data('action');
        layer.confirm('您确认操作吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url,$('#form-list').serialize(),function(data){
                showTip(data);
            });
        }, function(){});
    });
    //删除sql备份
    $(document).on('click','[data-del]',function(event){
        event.preventDefault();
        var url = $(this).data('del'),
            time = $(this).data('time');
        layer.confirm('您确定删除这个备份吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url,{time:time},function(data){
                showTip(data);
            });
        }, function(){});
    });
    //下载sql备份
    $(document).on('click','[data-down]',function(event){
        event.preventDefault();
        var url = $(this).data('down'),
            time = $(this).data('time');
        $.post(url,{time:time},function(data){
            window.location.href = data;
        });
    });
    //绑定排序事件
    $(document).on('click','[data-sort]',function(event){
        event.preventDefault();
        var url = $(this).data('sort');
        $.post(url,$('#form-list').serialize(),function(data){
            showTip(data);
        });
    });
    //绑定修改状态事件
    $(document).on('click','[data-status]',function(event){
        event.preventDefault();
        var cur = $(this),
            url = $(this).data('status'),
            id = $(this).data('id'),
            value = $(this).data('value');
        layer.confirm('您确认操作吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url,{id:id,value:value},function(data){
                layer.closeAll();
                if(data.code==1){
                    var news_title,news_tip,
                        old = value;
                    if(old == 0){
                        news_title="禁用";
                        news_tip='<span style="color:#090">使用中</span>';
                    }else{
                        news_title="启用";
                        news_tip="已禁用";
                    }
                    cur.data('value',data.data);
                    cur.html(news_title);
                    cur.parents('tr').find('.sc_td_status').html(news_tip);
                    layer.closeAll();
                }else{
                    return false;
                }
            });
        }, function(){});
    });
    //绑定修改状态事件
    $(document).on('click','[data-show]',function(event){
        event.preventDefault();
        var cur = $(this),
            url = $(this).data('show'),
            id = $(this).data('id'),
            value = $(this).data('value');
        layer.confirm('您确认操作吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url,{id:id,value:value},function(data){
                layer.closeAll();
                if(data.code==1){
                    var news_title,news_tip,
                        old = value;
                    if(old == 0){
                        news_title="隐藏";
                        news_tip='<span style="color:#090">显示中</span>';
                    }else{
                        news_title="显示";
                        news_tip="已隐藏";
                    }
                    cur.data('value',data.data);
                    cur.html(news_title);
                    cur.parents('tr').find('.show').html(news_tip);
                    layer.closeAll();
                }else{
                    return false;
                }
            });
        }, function(){});
    });
    $(document).on('mouseenter','[data-tips-text]',function(event){
        var text = $(this).attr('data-tips-text');
        layer.tips(text, $(this));
    });
    function open(url) {
        $('#sc_body').load(url,function (res) {
            $(".layui-form").Validform({
                tiptype:3,
                ajaxPost:true,
                beforeSubmit:function(curform){
                    $.post($('#form').attr('action'),$('#form').serialize(),function(data){
                        showTip(data);
                    });
                    return false;
                },
            });
            layer.closeAll();
            form.render();
        });
    };
    //倒计时弹出
    function showTip(data){
        var timer;
        if(data.code){
            layer.open({
                content: data.msg,
                closeBtn: 0,
                icon: 1,
                btn:[],
                success: function(a,b){
                    var i = 1;
                    var fn = function() {
                        layer.title(i + ' 秒后自动关闭。',b);
                        if(!i) {
                            switch (data.data) {
                                case 'login':
                                    window.location = data.url;
                                    break;
                                case 'page':
                                    href(data.url);
                                    break;
                            }
                            layer.close(b);
                            layer.closeAll();
                            if(data.url) open(data.url);
                        }
                        i--;
                    };
                    var timer = setInterval(fn, 1000);
                    fn();
                },
                cancel: function(i){
                    switch (data.data) {
                        case 'login':
                            window.location = data.url;
                            break;
                        case 'page':
                            href(data.url);
                            break;
                    }
                    layer.close(b);
                    layer.closeAll();
                    if(data.url) open(data.url);
                },
                end: function(){clearInterval(timer);}
            });
        }else{
            layer.open({
                content: data.msg,
                closeBtn: 0,
                icon: 2,
                btn:[],
                success: function(a,b){
                    var i = 2;
                    var fn = function() {
                        layer.title(i + ' 秒后自动关闭。',b);
                        if(!i) {layer.close(b); return false;} i--;
                    };
                    var timer = setInterval(fn, 1000);
                    fn();
                },
                cancel: function(i){
                    return false;
                },
                end: function(){clearInterval(timer);}
            });
        }
    }
});
// URL转URI
function parseUri(uri, obj){
    var params = {};
    if (uri.indexOf('?') !== -1) {
        var queryParams = uri.split('?')[1].split('&');
        for (var i in queryParams) {
            if (queryParams[i].indexOf('=') !== -1) {
                var hash = queryParams[i].split('=');
                try {
                    params[hash[0]] = window.decodeURIComponent(window.decodeURIComponent(hash[1].replace(/%2B/ig, ' ')));
                } catch (e) {
                    console.log([e, uri, queryParams, hash]);
                }
            }
        }
    }
    uri = this.getUri(uri);
    params.spm = obj && obj.getAttribute('data-menu-node') || this.queryNode(uri);
    if (!params.token) {
        var token = window.location.href.replace(/.*token=(\w+).*/ig, '$1');
        (/^\w{16}$/.test(token)) && (params.token = token);
    }
    delete params[""];
    var query = '?' + $.param(params);
    return uri + (query !== '?' ? query : '');
}
// 计算URL地址中有效的URI
function getUri(uri){
    uri = uri || window.location.href;
    uri = (uri.indexOf(window.location.host) !== -1 ? uri.split(window.location.host)[1] : uri).split('?')[0];
    return (uri.indexOf('#') !== -1 ? uri.split('#')[1] : uri);
}
// 通过URI查询最有可能的菜单NODE
function queryNode(url){
    var $menu = $('[data-menu-node][data-open*="_URL_"]'.replace('_URL_', url.replace(/\.html$/ig, '')));
    if ($menu.size()) {
        return $menu.get(0).getAttribute('data-menu-node');
    }
    return /^m\-/.test(node = location.href.replace(/.*spm=([\d\-m]+).*/ig, '$1')) ? node : '';
}
// url跳转
function href(url, obj){
    window.location.href = '#' + parseUri(url, obj);
}
// 获取url参数
function GetQueryString(name){
    var after = window.location.hash.split("?")[1];
    if(after){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = after.match(reg);
        if(r != null){
            return  decodeURIComponent(r[2]);
        }else{
            return null;
        }
    }
}
